package runesim.profileserv;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.*;
/**
 * Connection from here (profile server) to there (node).
 * @author Ben
 *
 */
public class NodeConnectionHandle implements ProfileTransferOpCodes, IConnectHandler, IDataHandler, IDisconnectHandler {
	
	@Override
	public boolean onConnect(INonBlockingConnection nbc) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
		nbc.setAttachment(0);
		return false;
	}
	
	@Override
	public boolean onData(INonBlockingConnection nbc) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
		int ecode = (Integer) nbc.getAttachment();
		
		try {
			byte opcode = nbc.readByte();
			
			switch(opcode){
				case NODE_HELLO: //Authorization of connecting node
					byte nodeID = nbc.readByte();
					
					if(ecode == 0){
						System.out.println("received hello from: "+nodeID);
						
						if((nodeID > 0 & nodeID < 120) & (nodeID == 1)){ //Evaluate everything... it is important to do so
							nbc.write(LS_AUTH);
							nbc.setAttachment(nodeID);
						} else {
							nbc.write(LS_BADAUTH);
							nbc.setAttachment(-1); //Force fail (below) = force re-establishment of connection
						}
					} else {
						//node trying to re-send it?
						//probably trying to hack or something
						//this will force connection exit and 
						//allow it to restore it once it has
						//re-authorized
						nbc.write(LS_BADAUTH);
						
						//had enough of this guy
						nbc.close();
					}
					break;
				
				case NODE_GET_PROFILE: //"All your logins are belong to us."
					long user = nbc.readLong(); //unique player name
					nbc.write(LS_PROFILE_RESPONSE); //packet header
					nbc.write(user); //Make sure it knows who we're talking about
					
					if(user == 0L){ //TODO Implement some validation (ifUserProfileExists() & ifPasswdMatch())
						if(false){ //User ban
							nbc.write((byte) runesim.shared.ResponseCodes.RESPONSE_BANNED);
						} else if(false){ //already logged in
							nbc.write((byte) runesim.shared.ResponseCodes.RESPONSE_LOGGED_IN);
						} else { //OK
							//TODO also implement sending of profile here
							nbc.write((byte) runesim.shared.ResponseCodes.RESPONSE_OK);
						}
					} else {
						nbc.write((byte) runesim.shared.ResponseCodes.RESPONSE_INVALID_LOGIN);
					}
					break;
			}
		} catch(Exception e){
			//encapsulate error
			System.out.println("protocol error");
			nbc.close();
		}
		return false;
	}
	
	@Override
	public boolean onDisconnect(INonBlockingConnection nbc) throws IOException {
		//lost connection to node
		System.out.println("lost connection to node");
		return false;
	}
}